<template>
  <div>
    <Page auto-content-height>
      <!-- 表格 -->
      <FosoTable
        :tool-bar-button-text="$t('sys.menu.addMenu')"
        table-title="菜单管理"
        table-titlehelp="菜单管理帮助"
        @add="openDrawerHandle('add', $event)"
      >
        <!-- 状态列 -->
        <template #status="{ row }">
          <StatusColumn :request-api="updateMenu" :row="row" />
        </template>
        <!-- 操作列 -->
        <template #action="{ row }">
          <OperationColumn
            :row="row"
            @delete="DeleteHandle($event)"
            @edit="openDrawerHandle('edit', $event)"
          />
        </template>
      </FosoTable>
    </Page>
    <!-- 弹窗框 -->
    <Drawer class="w-[40%]" @refresh="reloadTable" />
  </div>
</template>

<script setup lang="tsx">
import type { MenuInfoPlain } from '#/api/sys/model/menuModel';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { IconifyIcon as Icon } from '@vben/icons';
import { $t } from '@vben/locales';

import { ElTag } from 'element-plus';

import { deleteMenu, getMenuList, updateMenu } from '#/api/sys/menu';
import StatusColumn from '#/components/FosoTablePro/components/StatusColumn.vue';
import { OperationColumn } from '#/components/FosoTablePro/index';
import { useFosoTable } from '#/components/FosoTablePro/use-foso-config';
import { useFosoTableConfig } from '#/components/FosoTablePro/use-foso-table';

import ExtraDrawer from './components/drawer.vue';
import { type MenuItem, MenuTypeMap } from './type';

const [Drawer, drawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: ExtraDrawer,
});
// 数据过滤，将parentId为0的设置为null
const getMenuListData = async () => {
  const res = await getMenuList({ page: 1, pageSize: 5000 }); // 调用实际的 API 获取数据
  const data = res.data.map((item) => {
    return {
      ...item,
      parentId: item.parentId === 0 ? null : item.parentId,
    };
  });

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data,
        total: res.total,
      });
    }, 1000);
  });
};

// 使用 useFosoTable hook 生成配置
const { gridOptions } = useFosoTableConfig({
  columns: [
    {
      title: $t('sys.menu.menuName'),
      field: 'name',
      treeNode: true,
      width: 120,
      formatter: ({ cellValue }: any) => $t(`sys.menu.${cellValue}`), // 国际化
    },
    // 类型
    {
      title: $t('sys.menu.type'),
      field: 'menuType',
      minWidth: 119,
      formatter: ({ cellValue }: any) =>
        MenuTypeMap[cellValue as keyof typeof MenuTypeMap],
    },
    {
      title: $t('sys.menu.icon'),
      field: 'type',
      align: 'center',
      width: 100,
      slots: {
        default: (data: any) => {
          return (
            <div class="flex items-center justify-center">
              <Icon icon={data.row.icon} />
            </div>
          );
        },
      },
    },
    {
      title: $t('sys.menu.serviceName'),
      field: 'serviceName',
      minWidth: 120,
    },
    {
      title: $t('sys.menu.routePath'),
      field: 'path',
      minWidth: 120,
    },
    {
      title: $t('sys.menu.order'),
      field: 'sort',
      minWidth: 120,
    },
    // 状态
    {
      title: $t('sys.menu.status'),
      field: 'status',
      minWidth: 120,
      slots: {
        default: 'status',
      },
    },
    // 隐藏
    {
      title: $t('sys.menu.isHidden'),
      field: 'hideMenu',
      minWidth: 120,
      slots: {
        default: ({ row }: { row: MenuItem }) => {
          return (
            <ElTag type={row.hideMenu ? 'info' : 'success'}>
              {row.hideMenu ? $t('sys.menu.isHidden') : $t('sys.menu.isShown')}
            </ElTag>
          );
        },
      },
    },
    // 创建时间
    {
      title: $t('sys.menu.createTime'),
      field: 'createdAt',
      minWidth: 120,
      formatter: ['formatDate', 'yyyy-MM-dd'],
    },

    {
      title: $t('sys.menu.operation'),
      minWidth: 200,
      slots: { default: 'action' },
    },
  ],

  requestApi: getMenuListData,
  treeConfig: {
    transform: true,
    rowField: 'id',
    parentField: 'parentId',
  },
});

const { FosoTable, FosoTableApi } = useFosoTable(gridOptions);

/**
 * @author Buke
 * @description 打开弹窗
 * @param {string} type - 操作类型，'edit' 表示编辑，'add' 表示新增。
 * @param {MenuInfoPlain} row - 要编辑的行数据对象，包含字典相关信息。
 * @returns {void}
 */
const openDrawerHandle = (type: string, row?: MenuInfoPlain): void => {
  if (type === 'edit') {
    drawerApi.setState({ title: $t('sys.menu.editMenu') });
    drawerApi.setData({ type: 'editData', id: row?.id });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
  if (type === 'add') {
    drawerApi.setState({ title: $t('sys.menu.addMenu') });
    drawerApi.setData({ type: 'addData' });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
};

/**
 * @author Buke
 * @description 删除菜单
 * @param {MenuInfoPlain} row - 要删除的行数据。
 * @returns {void}
 */
async function DeleteHandle(row: MenuInfoPlain): Promise<void> {
  await deleteMenu(row.id!);
  ElMessage.success($t('common.deleteSuccess'));
  FosoTableApi.commitProxy('reload');
}

/**
 * @author Buke
 * @description 处理表格数据加载完成后的操作，如更新表格数据。
 * @returns {void}
 */
const reloadTable = (): void => {
  FosoTableApi.commitProxy('reload');
  drawerApi.close();
};
</script>
